package com.xuanyang.dormrepair.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanyang.dormrepair.model.entity.Advise;
import com.xuanyang.dormrepair.model.entity.FloorRoom;
import com.xuanyang.dormrepair.model.mapper.AdviseMapper;
import com.xuanyang.dormrepair.utils.PageKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;

/**
 * @AUTHOR soft
 * @DATE 2019/5/19 12:14
 * @DESCRIBE 建议
 */
@Service
@Slf4j
public class AdviseService implements IService<Advise> {

    @Autowired
    private AdviseMapper adviseMapper;

    @Autowired
    private FloorRoomService roomService;

    @Transactional
    public boolean add(Advise advise) {
        advise.setDatetime(new Date());
        return adviseMapper.insert(advise) > 0;
    }

    @Transactional
    public boolean delete(Serializable pk) {
        return adviseMapper.deleteById(pk) > 0;
    }

    @Transactional
    public boolean update(Advise advise) {
        return adviseMapper.updateById(advise) > 0;
    }

    @Override
    public Advise byId(Serializable pk) {
        Advise advise = adviseMapper.selectById(pk);
        if (advise != null) {
            advise.setRoom(roomService.byId(advise.getFloorId()));
        }
        return advise;
    }

    @Override
    public IPage<Advise> page(int page, int limit, Advise query) {
        LambdaQueryWrapper<Advise> wrapper = Wrappers.lambdaQuery(query);
        wrapper.orderByDesc(Advise::getId);

        IPage<Advise> iPage = adviseMapper.selectPage(PageKit.of(page, limit), wrapper);
        if (iPage.getTotal() > 0) {
            for (Advise advise : iPage.getRecords()) {
                FloorRoom room = roomService.byId(advise.getFloorId());
                advise.setRoom(room);
            }
        }
        return iPage;
    }
}
